<template>
  <div class="app-container home-page1">
    <div class="calender-header">
      <div class="left">
        <div v-for="color in markColorList" class="color-item" :key="color.id">
          <span class="color-block" :style="{ background: color.name }">&nbsp;</span>
          <span>{{ color.code === '9' ? '已占用' : '待审批' }}</span>
        </div>
        <el-button class="filter-item" style="margin-left: 10px" type="primary" icon="el-icon-plus" @click="openAddDialog('editForm')">申请会议室</el-button>
      </div>
      <div class="center">
        <el-button type="text" icon="el-icon-arrow-left" size="mini" @click="prev"></el-button>
        <el-date-picker :title="calendarParam.title" :clearable="false" :editable="false" v-model="calendarParam.titleValue" :format="calendarParam.titleFormat" size="small" style="width:135px;" value-format="yyyy-MM-dd" :type="calendarParam.titleType" placeholder="选择月" @change="changeCalendarDate"> </el-date-picker>
        <el-button type="text" icon="el-icon-arrow-right" size="mini" @click="next"></el-button>
      </div>
      <div class="right">
        <el-button type="default" size="mini" @click="today">今天</el-button>
        <el-radio-group v-model="calendarParam.currentView" @change="changeView" size="mini">
          <el-radio-button label="resourceTimelineDay">日</el-radio-button>
          <el-radio-button label="resourceTimelineWeek">周</el-radio-button>
        </el-radio-group>
      </div>
    </div>
    <div class="calendar-container" :style="{ height: calendarHeight + 'px' }">
      <tl-calendar ref="calendar" @dateClick="dateClick" @eventClick="eventClick" @eventSearch="eventSearch"  @datesSet="datesSet"></tl-calendar>
    </div>
    <div class="calendar-event-block" :style="{ top: eventBlock.top + 'px', left: eventBlock.left + 'px' }">
      <tl-room-apply-view ref="roomApplyForm"></tl-room-apply-view>
    </div>
    <tl-edit ref="editForm" @refresh="doRefresh"></tl-edit>
  </div>
</template>

<script>
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
import tlCalendar from '@/components/common/calendarRes'
import tlRoomApplyView from './roomApplyView'
import { getAction, putAction, postAction, deleteAction } from '@tapui/utils/http'
import { mixin_base } from '@tapui/mixins/mixin_base'
import { formatDate } from '@tapui/utils/date'
const { body } = document
import { queryDataCode } from '@tapui/api/dataCode'
import tlEdit from '../meetRoomApply/edit'
export default {
  mixins: [mixin_base, mixin_list],
  components: { tlCalendar, tlRoomApplyView, tlEdit },
  data() {
    return {
      url: {
        queryMeetRoomList: '/meet/roomManage/queryAllMeetRoom',
        queryApplyRecord: '/meet/roomManage/queryApplyRecord' // 会议室预约记录
      },
      calendarHeight: 500,
      events: [],
      markColorList: [],
      dateInfo: null,
      eventBlock: {
        top: 0,
        left: 0
      },
      viewUser: '',
      // 日历
      calendarParam: {
        instance: null,
        currentView: 'resourceTimelineWeek',
        start: '',
        end: '',
        title: '',
        titleValue: '',
        titleType: 'month',
        titleFormat: 'yyyy-MM'
      },
      resources: []
    }
  },
  methods: {
    // 初始化数据
    loadData() {
      // this.loadEvents({ qry_usercode: this.user.code })
    },
    /** 加载会议室 */
    loadRoom() {
      getAction(this.url.queryMeetRoomList, {})
        .then(res => {
          if (res.success) {
            this.resources = []
            res.result.forEach(item => {
              this.resources.push({
                id: item.id,
                key: item.type + '-' + item.sortcode, // 排序
                title: item.name,
                sortcode: item.sortcode,
                type: item.type
              })
            })
            this.calendarParam.instance.setOption('resourceAreaHeaderContent', '会议室')
            this.calendarParam.instance.setOption('resources', this.resources)
            // 设置资源排序顺序
            this.calendarParam.instance.setOption('resourceOrder', 'key')
          } else {
            this.$tap.message('获取会议室失败:' + res.message, 'error')
          }
        })
        .catch(_ => {
          this.$tap.message('获取会议室失败', 'error')
        })
    },
    // 日历事件
    eventSearch(info, successCallback, failureCallback) {
      let that = this
      getAction(this.url.queryApplyRecord, {
        qry_begintime: formatDate(new Date(info.startStr), 'yyyy-MM-dd HH:mm:ss'),
        qry_endtime: formatDate(new Date(info.endStr), 'yyyy-MM-dd HH:mm:ss')
      })
        .then(res => {
          if (res.success) {
            let events = []
            res.result.forEach(item => {
              events.push({
                id: item.id,
                title: item.name,
                start: item.begintime,
                end: item.endtime,
                resourceId: item.meetroomid,
                color: item.dispmarkcolor,
                username: item.username,
                telephone: item.telephone
              })
            })
            successCallback(events)
          } else {
            this.$tap.message('获取会议室预约记录失败:' + res.message, 'error')
            failureCallback('获取会议室预约记录失败:' + res.message, 'error')
          }
        })
        .catch(_ => {
          this.$tap.message('获取会议室预约记录失败', 'error')
          failureCallback('获取会议室预约记录失败', 'error')
        })
    },
    dateClick(info) {},
    /** 时间点击 */
    eventClick(info) {
      let applyInfo = {}
      applyInfo.name = info.event.title
      applyInfo.begintime = formatDate(new Date(info.event.start), 'yyyy-MM-dd HH:mm')
      applyInfo.endtime = formatDate(new Date(info.event.end), 'yyyy-MM-dd HH:mm')
      applyInfo.username = info.event.extendedProps.username
      applyInfo.telephone = info.event.extendedProps.telephone
      this.$refs['roomApplyForm'].model = applyInfo
      this.$refs['roomApplyForm'].visible = true
      this.$nextTick(_ => {
        this.chargeCalendarEditPosition(info)
      })
    },
    eventMouseEnter(info) {},
    eventMouseLeave(info) {
      this.$refs['roomApplyForm'].visible = false
    },
    // 时间显示方式
    slotLabelFormat: function(date) {
      if (this.calendarParam.currentView === 'resourceTimelineDay') {
        return `${(date.date.hour < 10 ? '0' : '') + date.date.hour}:${(date.date.minute < 10 ? '0' : '') + date.date.minute}`
      } else if (this.calendarParam.currentView === 'resourceTimelineWeek') {
        return `${date.date.month + '月' + date.date.date + '日'}(${date.date.day})`
      }
    },
    // 针对日历工具栏的二次开发
    changeView() {
      if (this.calendarParam.currentView === 'resourceTimelineDay') {
        // 日视图中，左侧时间显示方式
        this.calendarParam.instance.setOption('slotLabelInterval', { hours: 1 })
      } else if (this.calendarParam.currentView === 'resourceTimelineWeek') {
        this.calendarParam.instance.setOption('slotLabelInterval', { days: 1 })
      }
      this.calendarParam.instance.changeView(this.calendarParam.currentView)
    },
    prev() {
      this.calendarParam.instance.prev()
    },
    today() {
      this.calendarParam.instance.today()
    },
    next() {
      this.calendarParam.instance.next()
    },
    // 保存完刷新页面
    doRefresh() {
      this.$refs.calendar.refresh()
    },
    chargeCalendarEditPosition(info) {
      let { clientWidth: dayWidth, clientHeight: dayHeight } = info.dayEl || info.el
      let { clientWidth: formWidth, clientHeight: formHeight } = this.$refs.roomApplyForm.$el
      let { width: docWidth, height: docHeight } = body.getBoundingClientRect()
      let top = info.jsEvent.clientY + 10
      let left = info.jsEvent.clientX + 10

      // 正常情况下，显示在日期框的右边；若右侧超出屏幕，则显示在左侧；若下方超出屏幕，则显示在上方
      if (info.view.type === 'dayGridMonth') {
        left = left - info.jsEvent.offsetX
        top = top - info.jsEvent.offsetY
        if (top + formHeight > docHeight) {
          top = docHeight - formHeight - 20
        }
        if (left + dayWidth + formWidth > docWidth) {
          left = left - formWidth - 20
        } else {
          left = left + dayWidth
        }
      } else {
        if (left + formWidth > docWidth) {
          left = left - formWidth - 20
        }
        if (top + formHeight > docHeight) {
          top = docHeight - formHeight - 20
        }
      }

      this.eventBlock.top = top
      this.eventBlock.left = left
    },
    chargeCalendarViewPosition(info) {
      let { clientWidth: dayWidth, clientHeight: dayHeight } = info.dayEl || info.el
      let { clientWidth: formWidth, clientHeight: formHeight } = this.$refs.calendarEditForm.$el
      let { width: docWidth, height: docHeight } = body.getBoundingClientRect()
      let top = info.jsEvent.clientY + 10
      let left = info.jsEvent.clientX + 10

      if (left + formWidth > docWidth) {
        left = left - formWidth - 20
      }
      if (top + formHeight > docHeight) {
        top = docHeight - formHeight - 20
      }

      this.eventBlock.top = top
      this.eventBlock.left = left
    },
    resizeHandler() {
      // 134是页面多余位置，42是工具栏的高度
      this.calendarHeight = body.getBoundingClientRect().height - 186
    },
    // 日历切换时
    datesSet(dateInfo) {
      this.calendarParam.currentView = dateInfo.view.type
      this.calendarParam.title = dateInfo.view.title
      if (dateInfo.view.type.indexOf('Day') > -1) {
        this.calendarParam.titleType = 'date'
        this.calendarParam.titleFormat = 'yyyy-MM-dd'
        this.calendarParam.titleValue = formatDate(dateInfo.view.currentStart, 'yyyy-MM-dd')
      } else if (dateInfo.view.type.indexOf('Month') > -1) {
        this.calendarParam.titleType = 'month'
        this.calendarParam.titleValue = formatDate(dateInfo.view.currentStart, 'yyyy-MM-dd')
        this.calendarParam.titleFormat = 'yyyy-MM'
      } else {
        // 获取该年份1月1号星期数
        let week = new Date(formatDate(dateInfo.view.currentEnd, 'yyyy-01-01')).getDay()
        // 星期日返回值为0
        if (week === 0) {
          week = 7
        }
        // 获取第二周周一的日期
        let secondMonday = new Date(formatDate(dateInfo.view.currentEnd, 'yyyy-01-0' + (9 - week)))
        let weekNum = 1
        // 计算周数
        if (secondMonday.getTime() < dateInfo.view.currentEnd.getTime()) {
          weekNum = Math.ceil((dateInfo.view.currentEnd.getTime() - secondMonday.getTime()) / (7 * 24 * 60 * 60 * 1000)) + 1
        }
        this.calendarParam.titleType = 'week'
        this.calendarParam.titleFormat = 'yyyy第' + weekNum + '周'
        this.calendarParam.titleValue = formatDate(dateInfo.view.currentEnd, 'yyyy-MM-dd')
      }
      this.calendarParam.start = formatDate(dateInfo.view.currentStart, 'yyyy-MM-dd HH:mm:ss')
      this.calendarParam.end = formatDate(dateInfo.view.currentEnd, 'yyyy-MM-dd HH:mm:ss')
    },
    // 日历工具栏时间切换
    changeCalendarDate() {
      let date = this.calendarParam.titleValue
      this.calendarParam.instance.gotoDate(new Date(date))
    }
  },
  created() {
    this.viewUser = this.user.code
    queryDataCode({ itemCodes: 'MeetRoomColor' }).then(res => {
      this.markColorList = res.result.MeetRoomColor
    })
    this.loadRoom()
    this.resizeHandler()
    window.addEventListener('resize', this.resizeHandler)
    this.$nextTick(_ => {
      this.calendarParam.instance = this.$refs.calendar.$refs.calendar.getApi()
    })
  }
}
</script>

<style lang="scss">
.calendar-event-block {
  position: fixed;
  width: 430px;
  z-index: 1003;
}
.calendar-event-block-view {
  position: fixed;
  width: 350px;
  z-index: 1002;
}
.calender-header {
  margin-bottom: 10px;
  height: 32px;
  line-height: 32px;
  position: relative;
  .left {
    position: absolute;
    left: 0;
    top: 0;
    height: 32px;
    line-height: 32px;
    z-index: 10;
  }
  .right {
    position: absolute;
    right: 0;
    top: 0;
    height: 32px;
    line-height: 32px;
    z-index: 10;
    .el-radio-button--mini .el-radio-button__inner {
      padding: 7px 10px;
    }
  }
  .center {
    text-align: center;
    .el-button--mini {
      padding: 7px 10px;
    }
  }
}
</style>
<style scoped lang="scss">
.color-item {
  display: inline-block;
  margin-right: 10px;
  font-size: 14px;
  color: #777;
}
.color-block {
  height: 14px;
  width: 14px;
  padding: 0 2px;
  border-radius: 7px;
}
</style>
